using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace UnityEngine.AI
{
    /// <summary>
    /// 导出供后端使用的obj文件
    /// </summary>
    public class NavMeshDataExporter : MonoBehaviour
    {
        public void Export(string name = "")
        {
#if UNITY_EDITOR
            if (string.IsNullOrEmpty(name))
            {
                name = transform.gameObject.name;
            }
            
            NavMeshTriangulation triangulatedNavMesh = NavMesh.CalculateTriangulation();
           
            string path = Application.dataPath + "/navmesh/";
            string baseName = name;
            string filePath = path + baseName + ".obj";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            StreamWriter streamWriter = new StreamWriter(filePath);

            //顶点  
            for (int i = 0; i < triangulatedNavMesh.vertices.Length; i++)
            {
                streamWriter.WriteLine("v  " + triangulatedNavMesh.vertices[i].x + " " + triangulatedNavMesh.vertices[i].y + " " + triangulatedNavMesh.vertices[i].z);
            }

            streamWriter.WriteLine("g pPlane1");

            //索引  
            for (int i = 0; i < triangulatedNavMesh.indices.Length;)
            {
                streamWriter.WriteLine("f " + (triangulatedNavMesh.indices[i] + 1) + " " + (triangulatedNavMesh.indices[i + 1] + 1) + " " + (triangulatedNavMesh.indices[i + 2] + 1));
                i = i + 3;
            }

            //area区域
            for (int i = 0; i < triangulatedNavMesh.areas.Length; i++)
            {
                streamWriter.WriteLine("a " + triangulatedNavMesh.areas[i]);
            }

            streamWriter.Flush();
            streamWriter.Close();
            
            AssetDatabase.Refresh();
            
            Debug.Log("导出obj成功：" + filePath);
#endif

        }
        

        
    }
}